﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using System.Web;

namespace csharpApp
{
    class FileUploader
    {
        public FileSvr m_fileSvr = new FileSvr();
        HttpUploaderAppLib.HttpPartitionClass up6 = null;
        public dgt_msg show_msg = null;
        public JObject m_cfg = null;

        public FileUploader(HttpUploaderAppLib.HttpPartitionClass com)
        {
            this.up6 = com;
        }

        public void check_file()
        {
            Thread t = new Thread(delegate () {
                this.show_msg("------开始计算md5------");
                JObject o = new JObject();
                o["name"] = "check_file";
                o["id"] = this.m_fileSvr.id;
                o["pathLoc"] = this.m_fileSvr.pathLoc;
                this.up6.postMessage(o.ToString());
            });
            t.Start();
        }

        public void init_file() {
            Thread t = new Thread(delegate ()
            {
                this.show_msg("------文件初始化------");

                WebClient client = new WebClient();
                NameValueCollection nvc = new NameValueCollection();
                nvc.Add("md5", this.m_fileSvr.md5);
                nvc.Add("id", this.m_fileSvr.id);
                nvc.Add("uid", this.m_fileSvr.uid);
                nvc.Add("lenLoc", this.m_fileSvr.lenLoc.ToString());
                nvc.Add("sizeLoc", HttpUtility.UrlEncode(this.m_fileSvr.sizeLoc, Encoding.UTF8));
                nvc.Add("pathLoc", HttpUtility.UrlEncode(this.m_fileSvr.pathLoc, Encoding.UTF8));

                client.QueryString = nvc;
                Stream data = client.OpenRead(this.m_cfg["UrlCreate"].ToString());
                StreamReader reader = new StreamReader(data);
                string str = reader.ReadToEnd();
                this.show_msg("服务器初始化结果：");
                this.show_msg(str);
                data.Close();
                reader.Close();

                str = str.Remove(0, 1);
                str = str.Remove(str.Length-1,1);

                try
                {
                    var res = JObject.Parse(str);
                    str = HttpUtility.UrlDecode(res["value"].ToString(), Encoding.UTF8);
                    res = JObject.Parse(str);
                    this.m_fileSvr.pathSvr = res["pathSvr"].ToString();
                    //
                    this.init_file_complete();
                } catch (Exception e) {
                    this.init_file_error();
                }
            });
            t.Start();
        }

        public void init_file_complete() {
            this.post_file();
        }
        public void init_file_error() {
            this.show_msg("------文件初始化错误------");
        }

        /// <summary>
        /// 上传本地路径文件
        /// </summary>
        /// <param name="f">只需要提供pathLoc</param>
        public void post_file(FileSvr f)
        {
            this.m_fileSvr = f;
            //this.m_fileSvr.id = Guid.NewGuid().ToString("N");//38bddf48f43c48588e0d78761eaa1ce6
            //this.m_fileSvr.pathLoc = f.pathLoc;
            this.m_fileSvr.nameLoc = Path.GetFileName(f.pathLoc);

            Thread t = new Thread(delegate ()
            {
                this.show_msg("------文件初始化------");

                WebClient client = new WebClient();
                NameValueCollection nvc = new NameValueCollection();
                nvc.Add("op", "mkpath");
                nvc.Add("id", this.m_fileSvr.id);
                nvc.Add("pathLoc", HttpUtility.UrlEncode(this.m_fileSvr.pathLoc, Encoding.UTF8));

                client.QueryString = nvc;
                Stream data = client.OpenRead(this.m_cfg["UrlCreate"].ToString());
                StreamReader reader = new StreamReader(data);
                string str = reader.ReadToEnd();
                this.show_msg("服务器初始化结果：");
                this.show_msg(str);
                data.Close();
                reader.Close();

                try
                {
                    var res = JObject.Parse(str);
                    this.m_fileSvr.pathSvr = res["pathSvr"].ToString();

                    this.post_file();//开始上传
                    //
                } catch (Exception e) {
                    this.init_file_error();
                }
            });
            t.Start();
        }

        public void post_file()
        {
            this.show_msg("------开始上传 文件------");
            JObject o = new JObject();
            o["name"] = "post_file";
            o["id"] = this.m_fileSvr.id;
            JObject fields = new JObject();
            fields.Add("uid", this.m_fileSvr.uid);
            o["fields"] = fields;
            o["pathLoc"] = this.m_fileSvr.pathLoc;
            o["pathSvr"] = this.m_fileSvr.pathSvr;
            o["lenSvr"] = this.m_fileSvr.lenSvr.ToString();
            this.up6.postMessage(o.ToString());
        }

        public void md5_process(JToken o) { }
        public void md5_complete(JToken o) {
            this.m_fileSvr.md5 = o["md5"].ToString();
            this.show_msg("------md5计算完毕------");
            this.show_msg(string.Format("md5:{0}", o["md5"]));

            this.init_file();
        }
        public void md5_error(JToken o)
        {
            this.show_msg("------md5计算错误------");
            this.show_msg(string.Format("file:{0}", this.m_fileSvr.pathLoc));
        }
        public void post_process(JToken o)
        {
            this.m_fileSvr.lenSvr = Convert.ToInt64( o["lenSvr"] );
            this.m_fileSvr.perSvr = o["percent"].ToString();

            this.show_msg("------文件上传中------");
            this.show_msg(string.Format("进度:{0},已传：{1},速度：{2},剩余时间：{3}",
                o["percent"],
                o["lenPost"],
                o["speed"],
                o["time"]));
        }
        public void post_complete(JToken o)
        {
            WebClient client = new WebClient();
            NameValueCollection nvc = new NameValueCollection();
            nvc.Add("md5", this.m_fileSvr.md5);
            nvc.Add("id", this.m_fileSvr.md5);
            nvc.Add("uid", this.m_fileSvr.uid);
            nvc.Add("pid", this.m_fileSvr.pid);

            client.QueryString = nvc;
            Stream data = client.OpenRead(this.m_cfg["UrlComplete"].ToString());
            StreamReader reader = new StreamReader(data);
            string str = reader.ReadToEnd();
            this.show_msg("执行结果：");
            this.show_msg(str);
            data.Close();
            reader.Close();

            str = str.Remove(0, 1);
            str = str.Remove(str.Length - 1, 1);

            try
            {
            }
            catch (Exception e)
            {
            }

            this.show_msg("------文件上传完毕------");
            this.show_msg(string.Format("进度:100%"));
        }
        public void post_error(JToken o)
        {
            this.show_msg("------文件上传错误------");
        }
        public void scan_process(JToken o) { }
        public void scan_complete(JToken o) { }
    }
}